<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="条件名称" prop="conditionName">
        <el-input
          v-model="queryParams.conditionName"
          placeholder="请输入条件名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="职业代码" prop="professionCode">
        <el-select
          v-model="queryParams.professionCode"
          placeholder="请选择职业代码"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="profession in professionList"
            :key="profession.professionCode"
            :label="`${profession.professionCode}（${profession.professionName}）`"
            :value="profession.professionCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="技能等级" prop="skillLevel">
        <el-select
          v-model="queryParams.skillLevel"
          placeholder="请选择技能等级"
          clearable
          class="!w-240px"
        >
          <el-option label="五级" value="五级" />
          <el-option label="四级" value="四级" />
          <el-option label="三级" value="三级" />
          <el-option label="二级" value="二级" />
          <el-option label="一级" value="一级" />
        </el-select>
      </el-form-item>
      <el-form-item label="评价方式" prop="evaluationMethod">
        <el-select
          v-model="queryParams.evaluationMethod"
          placeholder="请选择评价方式"
          clearable
          class="!w-240px"
        >
          <el-option label="认定评价" value="assessment" />
          <el-option label="考试评价" value="examination" />
          <el-option label="混合评价" value="mixed" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="conditionStatus">
        <el-select
          v-model="queryParams.conditionStatus"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="条件名称" align="center" prop="conditionName" width="150" />
      <el-table-column label="职业代码" align="center" prop="professionCode" width="200">
        <template #default="scope">
          {{ getProfessionDisplayName(scope.row.professionCode) }}
        </template>
      </el-table-column>
      <el-table-column label="技能等级" align="center" prop="skillLevel" width="100" />
      <el-table-column label="评价方式" align="center" prop="evaluationMethod" width="120">
        <template #default="scope">
          {{ getEvaluationMethodName(scope.row.evaluationMethod) }}
        </template>
      </el-table-column>
      <el-table-column label="条件类型" align="center" prop="conditionType" width="120">
        <template #default="scope">
          {{ getConditionTypeName(scope.row.conditionType) }}
        </template>
      </el-table-column>
      <el-table-column label="是否必需" align="center" prop="isRequired" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.isRequired ? 'success' : 'info'">
            {{ scope.row.isRequired ? '必需' : '可选' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="conditionOrder" width="80" />
      <el-table-column label="状态" align="center" prop="conditionStatus" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.conditionStatus === 1 ? 'success' : 'danger'">
            {{ scope.row.conditionStatus === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="handleCopy(scope.row)"
          >
            复制
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ConditionForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <ConditionDetail ref="detailRef" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import {
  EvalApplicationConditionVO,
  EvalApplicationConditionPageReqVO,
  getApplicationConditionPage,
  deleteApplicationCondition,
  exportApplicationCondition
} from '@/api/eval/condition'
import { getSimpleProfessionList } from '@/api/eval/profession'
import ConditionForm from './ConditionForm.vue'
import ConditionDetail from './ConditionDetail.vue'

/** 申报条件配置 列表 */
defineOptions({ name: 'EvalCondition' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalApplicationConditionVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive<EvalApplicationConditionPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  conditionName: undefined,
  professionCode: undefined,
  skillLevel: undefined,
  evaluationMethod: undefined,
  conditionStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const professionList = ref<any[]>([]) // 职业列表

/** 获取评价方式名称 */
const getEvaluationMethodName = (method: string) => {
  const methodMap = {
    'assessment': '认定评价',
    'examination': '考试评价',
    'mixed': '混合评价'
  }
  return methodMap[method] || '-'
}

/** 获取条件类型名称 */
const getConditionTypeName = (type: string) => {
  const typeMap = {
    'education': '学历要求',
    'work_experience': '工作年限',
    'training': '培训经历',
    'certificate': '证书要求',
    'other': '其他要求'
  }
  return typeMap[type] || '-'
}

/** 获取职业代码显示名称 */
const getProfessionDisplayName = (professionCode: string) => {
  const profession = professionList.value.find(p => p.professionCode === professionCode)
  return profession ? `${profession.professionCode}（${profession.professionName}）` : professionCode
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    console.log('查询参数:', queryParams)
    const data = await getApplicationConditionPage(queryParams)
    console.log('查询结果:', data)
    list.value = data.list
    total.value = data.total
    console.log('列表数据:', list.value)
    console.log('总数:', total.value)
  } catch (error) {
    console.error('查询失败:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 复制操作 */
const handleCopy = (row: EvalApplicationConditionVO) => {
  const copyData = { ...row }
  delete copyData.id
  delete copyData.createTime
  delete copyData.updateTime
  copyData.conditionName = copyData.conditionName + '（复制）'
  formRef.value.open('create', undefined, copyData)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteApplicationCondition(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportApplicationCondition(queryParams)
    download.excel(data, '申报条件配置.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取职业列表 */
const loadProfessionList = async () => {
  try {
    const data = await getSimpleProfessionList()
    professionList.value = data || []
  } catch (error) {
    console.error('获取职业列表失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  loadProfessionList()
  getList()
})
</script>
